﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace DataLayer.BD
{
	public class Connection
	{
		SqlCommand cmd;
		//private string ConnectionString = @"Data Source=SANDER-PC;Initial Catalog=Bybike;Integrated Security=True";
		private string ConnectionString = @"Data Source=174.36.55.140;Initial Catalog=ByBike;Persist Security Info=True;User ID=bybike;Password=b1b1k3sh0p";

		public SqlConnection GetConnection { get { return new SqlConnection() { ConnectionString = ConnectionString }; } }

		public int Insert(string _sqlQuery, string _idField, string _tableName)
		{
			cmd = new SqlCommand(_sqlQuery, GetConnection);
			try
			{
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
				cmd.Connection.Close();

				int lastID = 0;

				cmd = new SqlCommand("select max(" + _idField + ") from " + _tableName, GetConnection);
				cmd.Connection.Open();
				SqlDataAdapter da = new SqlDataAdapter(cmd);
				DataTable dt = new DataTable();
				da.Fill(dt);

				int.TryParse(dt.Rows[0][0].ToString(), out lastID);

				cmd.Connection.Close();
				return lastID;
			}
			catch (Exception)
			{
				cmd.Connection.Close();
				throw;
			}
		}
		public void Update(string _sqlQuery)
		{
			cmd = new SqlCommand(_sqlQuery, GetConnection);
			try
			{
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
				cmd.Connection.Close();
			}
			catch (Exception)
			{
				cmd.Connection.Close();
				throw;
			}
		}
		public DataTable Select(string _sqlQuery)
		{
			try
			{
				cmd = new SqlCommand(_sqlQuery, GetConnection);
				cmd.Connection.Open();
				SqlDataAdapter da = new SqlDataAdapter(cmd);
				DataTable dt = new DataTable();
				da.Fill(dt);
				cmd.Connection.Close();
				return dt;
			}
			catch (Exception)
			{
				cmd.Connection.Close();
				throw;
			}
		}
		public void Delete(string _sqlQuery)
		{
			cmd = new SqlCommand(_sqlQuery, GetConnection);
			try
			{
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
				cmd.Connection.Close();
			}
			catch (Exception)
			{

				throw;
			}
		}

	}
}
